/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI.TOOL;

import GUI.Login;
import POJO.CauHinh;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;

/**
 *
 * @author Khôi
 */
public class CreateDatabase extends javax.swing.JFrame {

	/**
	 * Creates new form CreateDatabase Chức năng : Tạo CSDL sau đó lấy tập
	 * tin backup de chép đè lên Tên CSDL QL Xóa CSDL tên QLBH
	 */
	public CreateDatabase() {
		initComponents();
		IOUtils docCauHinh = new IOUtils();
		try {
			CauHinh ch = new CauHinh();
			int t = docCauHinh.ReadFile("config.ini", ch);
			if (t == 1) {
				txServer.setText(ch.getServer());
				txMasster.setText(ch.getMasster());
				txDatabase.setText(ch.getDatabase());
				txUser.setText(ch.getUser());
				txPass.setText(ch.getPass());
				txPath.setText(ch.getPath());
			}
			//tmp.ReadFile("test.ini", str1, str2);

		} catch (IOException e) {
		}
	}

	/**
	 * This method is called from within the constructor to initialize the
	 * form. WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
       // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
       private void initComponents() {

              txMasster = new javax.swing.JTextField();
              jButton1 = new javax.swing.JButton();
              jLabel1 = new javax.swing.JLabel();
              jLabel2 = new javax.swing.JLabel();
              txDatabase = new javax.swing.JTextField();
              jLabel3 = new javax.swing.JLabel();
              txUser = new javax.swing.JTextField();
              jButton2 = new javax.swing.JButton();
              jLabel4 = new javax.swing.JLabel();
              txPass = new javax.swing.JTextField();
              jLabel5 = new javax.swing.JLabel();
              jLabel6 = new javax.swing.JLabel();
              txPath = new javax.swing.JTextField();
              jLabel7 = new javax.swing.JLabel();
              txServer = new javax.swing.JTextField();
              jLabel8 = new javax.swing.JLabel();
              txPort = new javax.swing.JTextField();

              setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
              setTitle("Tạo CSDL");

              txMasster.setText("master");

              jButton1.setText("Tạo database");
              jButton1.setToolTipText("Tạo database tên QL");
              jButton1.addActionListener(new java.awt.event.ActionListener() {
                     public void actionPerformed(java.awt.event.ActionEvent evt) {
                            jButton1ActionPerformed(evt);
                     }
              });

              jLabel1.setText("Database master:");

              jLabel2.setText("Tên database sẽ tạo:");

              txDatabase.setText("QLBH");

              jLabel3.setText("User sử dụng:");

              txUser.setText("nhom1");

              jButton2.setText("Xóa database");
              jButton2.setToolTipText("Xóa database tên QL");
              jButton2.addActionListener(new java.awt.event.ActionListener() {
                     public void actionPerformed(java.awt.event.ActionEvent evt) {
                            jButton2ActionPerformed(evt);
                     }
              });

              txPass.setText("123");

              jLabel5.setText("Pass của user trên:");

              jLabel6.setText("Đường dẫn:");

              txPath.setText("C:\\QLBH.bak");

              jLabel7.setText("Server name:");

              txServer.setText("localhost");

              jLabel8.setText("Port:");

              txPort.setText("1433");

              javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
              getContentPane().setLayout(layout);
              layout.setHorizontalGroup(
                     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButton2)
                            .addGap(105, 105, 105))
                     .addGroup(layout.createSequentialGroup()
                            .addGap(94, 94, 94)
                            .addComponent(jLabel4)
                            .addGap(405, 413, Short.MAX_VALUE))
                     .addGroup(layout.createSequentialGroup()
                            .addGap(92, 92, 92)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                   .addComponent(jLabel7)
                                   .addComponent(jLabel1)
                                   .addComponent(jLabel2)
                                   .addComponent(jLabel3)
                                   .addComponent(jLabel5)
                                   .addComponent(jLabel6)
                                   .addComponent(jLabel8))
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                   .addComponent(txPort, javax.swing.GroupLayout.Alignment.TRAILING)
                                   .addComponent(txPath)
                                   .addComponent(txServer)
                                   .addComponent(txMasster)
                                   .addComponent(txDatabase)
                                   .addComponent(txUser)
                                   .addComponent(txPass))
                            .addContainerGap())
              );
              layout.setVerticalGroup(
                     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addGroup(layout.createSequentialGroup()
                            .addGap(35, 35, 35)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                   .addComponent(txServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                   .addComponent(jLabel7))
                            .addGap(5, 5, 5)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                   .addComponent(txPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                   .addComponent(jLabel8))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                   .addComponent(txMasster, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                   .addComponent(jLabel1))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                   .addComponent(txDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                   .addComponent(jLabel2))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                   .addComponent(txUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                   .addComponent(jLabel3))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                   .addComponent(txPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                   .addComponent(jLabel4)
                                   .addComponent(jLabel5))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                   .addComponent(txPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                   .addComponent(jLabel6))
                            .addGap(8, 8, 8)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                   .addComponent(jButton1)
                                   .addComponent(jButton2))
                            .addContainerGap(16, Short.MAX_VALUE))
              );

              pack();
       }// </editor-fold>//GEN-END:initComponents

	public boolean taoDatabase(String data, String user, String pass) {
		try {

			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			Connection conn = DriverManager.getConnection(data, user, pass);
			System.out.println("connected");
			Statement statement = conn.createStatement();
			String queryString = "create database " + txDatabase.getText().trim() + ";";
			int rs = 0;
			try {
				rs = statement.executeUpdate(queryString);

			} catch (SQLException e) {
				System.out.println("Không thể tạo CSDL");
				JOptionPane.showMessageDialog(this, "Không thể tạo CSDL", "Thông báo lỗi", JOptionPane.ERROR_MESSAGE);
				conn.close();
				this.setVisible(true);
				return false;
			}
			System.out.println(rs + " Tạo xong data");
			boolean flag = false;
			String res = "RESTORE DATABASE " + txDatabase.getText().trim() + " FROM DISK = '" + txPath.getText() + "' WITH REPLACE, NOUNLOAD, STATS = 10;";
			try {
				flag = statement.execute(res);

			} catch (SQLException e) {
				JOptionPane.showMessageDialog(this, "Không thể restore CSDL", "Thông báo lỗi", JOptionPane.ERROR_MESSAGE);

				System.out.println("Không thể restore CSDL");
				conn.close();
				this.setVisible(true);

				return false;
			}

			System.out.println(flag + " Restore xong ");
			conn.close();
			System.out.println("Đón kết nối ");

		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	public boolean tao() {
		String ketNoiMasster = "jdbc:sqlserver://"
			 + txServer.getText().trim()
			 + ":" + txPort.getText().trim()
			 + ";databaseName=" + txMasster.getText().trim()
			 + ";";
		boolean flag = taoDatabase(ketNoiMasster, txUser.getText().trim(), txPass.getText().trim());
		return flag;
	}
       private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
		// TODO add your handling code here:
		IOUtils ghiCauHinh = new IOUtils();
		CauHinh ch = new CauHinh();
		try {
			ch.setServer(txServer.getText().trim());
			ch.setPort(txPort.getText().trim());
			ch.setMasster(txMasster.getText().trim());
			ch.setDatabase(txDatabase.getText().trim());
			ch.setUser(txUser.getText().trim());
			ch.setPass(txPass.getText().trim());
			ch.setPath(txPath.getText().trim());

			ghiCauHinh.Write2File("config.ini", ch);

		} catch (IOException e) {
		}

		if (tao()) {
			try {
				Login.btLogin.setVisible(true);
				Login.btTaoCSDL.setVisible(false);
			} catch (Exception e) {
			}

			JOptionPane.showMessageDialog(this, "Đã tạo xong CSDL ", "Thông báo thành công", JOptionPane.INFORMATION_MESSAGE);


		}
       }//GEN-LAST:event_jButton1ActionPerformed

       private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
		// TODO add your handling code here:
		xoa();

       }//GEN-LAST:event_jButton2ActionPerformed
	public void xoa() {
		String ketNoiMasster = "jdbc:sqlserver://"
			 + txServer.getText().trim()
			 + ":" + txPort.getText().trim()
			 + ";databaseName=" + txMasster.getText().trim()
			 + ";";
		xoaDatabase(ketNoiMasster + ";", txUser.getText().trim(), txPass.getText().trim());
	}

	public void xoaDatabase(String data, String user, String pass) {
		try {

			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			Connection conn = DriverManager.getConnection(data, user, pass);
			System.out.println("Đã kết nối");
			Statement statement = conn.createStatement();
			String queryString = "drop database " + txDatabase.getText().trim();
			int rs = 0;
			try {
				rs = statement.executeUpdate(queryString);

			} catch (SQLException e) {
				System.out.println("Không thể xóa  CSDL");
				JOptionPane.showMessageDialog(this, "Không thể xóa CSDL", "Thông báo lỗi", JOptionPane.ERROR_MESSAGE);
				conn.close();
				this.setVisible(true);

				return;
			}
			System.out.print(" Sau khi xóa thành công kq = " + rs);
			conn.close();

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Không thể xóa CSDL");
			return;

		}
	}

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
		 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(CreateDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		//</editor-fold>

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new CreateDatabase().setVisible(true);
			}
		});
	}
       // Variables declaration - do not modify//GEN-BEGIN:variables
       private javax.swing.JButton jButton1;
       private javax.swing.JButton jButton2;
       private javax.swing.JLabel jLabel1;
       private javax.swing.JLabel jLabel2;
       private javax.swing.JLabel jLabel3;
       private javax.swing.JLabel jLabel4;
       private javax.swing.JLabel jLabel5;
       private javax.swing.JLabel jLabel6;
       private javax.swing.JLabel jLabel7;
       private javax.swing.JLabel jLabel8;
       private javax.swing.JTextField txDatabase;
       private javax.swing.JTextField txMasster;
       private javax.swing.JTextField txPass;
       private javax.swing.JTextField txPath;
       private javax.swing.JTextField txPort;
       private javax.swing.JTextField txServer;
       private javax.swing.JTextField txUser;
       // End of variables declaration//GEN-END:variables
}
